import utils from '@/utils/index';
import { Image, Swiper, SwiperItem, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import AdvertRecommend from '../advertRecommend';

/**
 *
 * @param {*} react false/undefined 表示后台控制;  true 表示 width 和 height 为100%;  其它 {width: xxx, height: xxx}
 */
const Advert = ({
  dispatch,
  alias,
  prefix = alias,
  advert,
  react,
  goTxt,
  onClick,
  onAdvertInfo,
}) => {
  // 拼接前缀
  const advertInfo = advert[`${prefix}AdvertInfo`];
  const advertList = advert[`${prefix}AdvertList`];

  const handleClick = () => {
    if (onClick) {
      onClick({
        advertInfo,
        advertList,
      });
      return;
    }

    if (advertList[0].url) {
      Taro.navigateTo({ url: advertList[0].url });
    }
  };

  // 获取广告内容
  useEffect(() => {
    dispatch({
      type: 'otherApi/getAdvert',
      payload: { alias, prefix },
    });
  }, [prefix, alias]);

  // 触发 广告信息回传
  useEffect(() => {
    if (onAdvertInfo && advertInfo) {
      onAdvertInfo({ advertInfo, advertList });
    }
  }, [onAdvertInfo, advertInfo, advertList]);

  if (!advertInfo) {
    return null;
  }

  let imgStyle;
  if (react === false || react === undefined) {
    imgStyle = {
      width: utils.getSizeByScale(advertInfo.wide) + 'px',
      height: utils.getSizeByScale(advertInfo.high) + 'px',
    };
  } else if (react === true) {
    imgStyle = {
      width: '100%',
      height: '100%',
    };
  } else {
    imgStyle = react;
  }

  if (advertInfo.type === 4) {
    return <AdvertRecommend {...{ imgStyle, advertInfo, advertList, goTxt, onClick }} />;
  }

  return (
    <>
      {advertList.length == 1 && (
        <View className="banner" onClick={handleClick} style={imgStyle}>
          <Image style={{ width: '100%', height: '100%' }} src={advertList[0].imageUrl} />
        </View>
      )}
      {advertList.length > 1 && (
        <Swiper
          className="banner"
          indicatorColor="rgba(245,245,245,0.5)"
          indicatorActiveColor="#999"
          circular
          indicatorDots
          autoplay
          style={{
            width: utils.getSizeByScale(advertInfo.wide) + 'px',
            height: utils.getSizeByScale(advertInfo.high) + 'px',
          }}
        >
          {advertList.map((ad, index) => (
            <SwiperItem key={'swipicture' + '_' + index} onClick={onClick}>
              <Image className="bannerIcon" src={ad.imageUrl} key={'swiperImage' + index} />
            </SwiperItem>
          ))}
        </Swiper>
      )}
    </>
  );
};

export default connect(({ otherApi }) => ({
  advert: Object.keys(otherApi).reduce((r, key) => {
    if (/AdvertInfo$/.test(key) || /AdvertList/.test(key)) {
      r[key] = otherApi[key];
    }

    return r;
  }, {}),
}))(Advert);
